package com.sunjob.mroimg.interceptor;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.sunjob.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Wangzurong
 * @create 2022-08-10 17:21
 * 实现敏感图片拦截
 */
@Slf4j
public class ImgInterceptor implements HandlerInterceptor {
    /**
     * 访问图片路径进行鉴权
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        log.info(requestURI);
        if(Pattern.matches("/img/private/.*",requestURI)){
            // 鉴权
            response.setHeader("Content-Type","application/json;charset=UTF-8");
            if(!StpUtil.isLogin()){
                response.getWriter().println(JSON.toJSONString(Result.fail("用户未登录")));
                return false;
            }
            List<String> permissionList = StpUtil.getPermissionList();
            for(String t:permissionList){
                if(t.equals("tool:img:view")){
                    return true;
                }
            }
            response.getWriter().println(JSON.toJSONString(Result.fail("你无权访问该路径下的文件")));
            return false;
        }else{
            return true;
         }
    }
}
